package com.hmall.gateway.filters;

import com.hmall.common.exception.UnauthorizedException;
import com.hmall.gateway.config.AuthProperties;
import com.hmall.gateway.utils.JwtTool;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.HttpStatusCode;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.util.AntPathMatcher;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.lang.annotation.Annotation;
import java.util.List;

@Component
public class AuthGlobalFilter implements GlobalFilter,Order {
    @Autowired
    private AuthProperties authProperties;
    @Autowired
    private JwtTool jwtTool;
    private AntPathMatcher antPathMatcher = new AntPathMatcher();

    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        System.out.println("path:"+request.getPath().value());
        if(isExcludePath(request.getPath().toString())){
            return chain.filter(exchange);
        }
        List<String> headers = request.getHeaders().get("authorization");
        String token=null;
        if(headers != null && !headers.isEmpty()){
            token = headers.get(0);
        }
        Long userId=null;
        try {
             userId= jwtTool.parseToken(token);
        }catch (UnauthorizedException e){
            ServerHttpResponse response = exchange.getResponse();
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        String userInfo = userId.toString();
        ServerWebExchange swe = exchange.mutate().request(builder -> builder.header("user-info",userInfo )).build();

        return chain.filter(swe);
    }
    private boolean isExcludePath(String string) {
        for (String path : authProperties.getExcludePaths()) {
            System.out.println(path);
            if (antPathMatcher.match(path, string)) {
                return true;
            }
        }
        return false;
    }
    @Override
    public int value() {
        return 0;
    }
    @Override
    public Class<? extends Annotation> annotationType() {
        return null;
    }
}
